package org.aurora.framework.boot.data.mybatis.type;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.aurora.framework.boot.common.enums.Enumerator;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * EnumerateTypeHandler
 * <pre>
 * description: 枚举类型数据转换
 * create date: 2025-03-15 20:03:34
 * </pre>
 *
 * @author cao.yong
 */
public class EnumerateTypeHandler<E extends Enumerator> extends BaseTypeHandler<E> {

    private final Class<E> enumerator;

    public EnumerateTypeHandler(Class<E> enumerator) {
        if (enumerator == null) throw new IllegalArgumentException("Type argument cannot be null");
        this.enumerator = enumerator;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Enumerator parameter, JdbcType jdbcType) throws SQLException {
        ps.setInt(i, null == parameter ? 0 : parameter.getValue());
    }

    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return Enumerator.fromValue(enumerator, rs.getInt(columnName)).orElse(null);
    }

    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return Enumerator.fromValue(enumerator, rs.getInt(columnIndex)).orElse(null);
    }

    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return Enumerator.fromValue(enumerator, cs.getInt(columnIndex)).orElse(null);
    }
}
